package com.xingdata.jjxc.utils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.ab.activity.AbActivity;

public class CameraUtils {

	private final static String FILE_SAVEPATH = Environment
			.getExternalStorageDirectory().getAbsolutePath() + "/zzd/portrait/";
	private final static int CROP = 200;

	private static Uri cropUri;
	private static File protraitFile;
	private static String protraitPath;

	// 拍照保存的绝对路�??
	public static Uri getCameraTempFile(AbActivity avty, Uri origUri) {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			avty.showToast("无法保存上传的头像，请检查SD卡是否挂�?");
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		// 照片命名
		String cropFileName = "osc_camera_" + timeStamp + ".jpg";
		// 裁剪头像的绝对路�??
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);
		cropUri = Uri.fromFile(protraitFile);
		origUri = cropUri;
		return cropUri;
	}

	// 裁剪头像的绝对路�??
	public static Uri getUploadTempFile(Activity avty, Uri uri) {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			Toast.makeText(avty, "无法保存上传的头像，请检查SD卡是否挂失", Toast.LENGTH_SHORT);
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

		// 如果是标准Uri
		if (Fmt.isEmpty(thePath)) {
			thePath = ImageUtils.getAbsoluteImagePath(avty, uri);
		}
		String ext = Fmt.getFileFormat(thePath);
		ext = Fmt.isEmpty(ext) ? "jpg" : ext;
		// 照片命名
		String cropFileName = "zzd_" + timeStamp + "." + ext;
		// 裁剪头像的绝对路�??
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);

		cropUri = Uri.fromFile(protraitFile);
		return cropUri;
	}

	/**
	 * 拍照后裁�??
	 * 
	 * @param data
	 *            原始图片
	 * @param output
	 *            裁剪后图�??
	 */
	public static Intent startActionCrop(Activity avty, Uri data) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(data, "image/*");
		intent.putExtra("output", getUploadTempFile(avty, data));
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// 裁剪框比�??
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", CROP);// 输出图片大小
		intent.putExtra("outputY", CROP);
		intent.putExtra("scale", true);// 去黑�??
		intent.putExtra("scaleUpIfNeeded", true);// 去黑�??
		intent.putExtra("return-data", true);
		// avty.startActivityForResult(intent,
		// ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
		return intent;
	}

	/**
	 * 选择图片后裁�??
	 * 
	 * @param data
	 *            原始图片
	 * @param output
	 *            裁剪后图�??
	 */
	public static Intent chooseImgActionCrop(Activity avty) {
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		// intent.putExtra("output", getUploadTempFile(avty, data));
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// 裁剪框比�??
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", CROP);// 输出图片大小
		intent.putExtra("outputY", CROP);
		intent.putExtra("scale", true);// 去黑�??
		intent.putExtra("scaleUpIfNeeded", true);// 去黑�??
		intent.putExtra("return-data", true);
		// avty.startActivityForResult(intent,
		// ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
		return intent;
	}

	/**
	 * 上传新照�??
	 */
	public static Bitmap display(Intent intent, ImageView photo) {
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			Bitmap pic = bundle.getParcelable("data");
			photo.setVisibility(View.VISIBLE);
			photo.setImageBitmap(pic);
			return pic;
		} else {
			return null;
		}
	}

	public static void startActionCamera(AbActivity avty, Uri origUri) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				getCameraTempFile(avty, origUri));
		avty.startActivityForResult(intent,
				ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
	}

	/**
	 * 上传图片
	 * 
	 * @param uri
	 * @param pic
	 * @param img_type
	 *            |
	 * @param "1" - 商品图片
	 * @param "2" - 会员图片
	 * @param "3" - 雇员图片
	 * @param "4" - 门店图片
	 * @param "5" - 老板图片
	 * @param img_name
	 */
	public static void upload(String uri, String access_token, String userid,
			String type, String filepath, String img_name, Bitmap pic) {

		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();

		HttpPost httpPost = new HttpPost(uri);
		MultipartEntity entity = new MultipartEntity(
				HttpMultipartMode.BROWSER_COMPATIBLE);

		Bitmap bmpCompressed = Bitmap.createScaledBitmap(pic, 480, 480, true);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		bmpCompressed.compress(CompressFormat.JPEG, 30, bos);
		byte[] data = bos.toByteArray();

		File file = getFile(data, filepath, img_name + ".jpg");

		try {
			entity.addPart("access_token", new StringBody(access_token));
			entity.addPart("userid", new StringBody(userid));
			entity.addPart("type", new StringBody(type));
			entity.addPart("image", (ContentBody) file);

			// entity.addPart("image", new ByteArrayBody(data, img_name +
			// ".jpg"));
			httpPost.setEntity(entity);

			HttpResponse response = httpClient.execute(httpPost, localContext);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse = reader.readLine();
			Log.i("PIC", "响应�?: " + sResponse);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据byte数组，生成文�??
	 */
	public static File getFile(byte[] bfile, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
				dir.mkdirs();
			}
			file = new File(filePath + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bfile);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return file;
	}
}
